package com.example.demo.utils;

import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.*;

@Slf4j
public class DbConnectionUtils {

    public static List<Map<String, String>> executeQuery(String driver, String url, String user, String password, String sql) {
        //初始化连接
        Connection connection;
        List<Map<String, String>> mapList = new ArrayList<>();
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, user, password);
            //判断连接是否成功
            if (!connection.isClosed()) {
                Statement statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery(sql);
                ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
                while (resultSet.next()) {
                    int columnCount = resultSetMetaData.getColumnCount();
                    Map<String, String> map = new HashMap<>();
                    for (int i = 1; i <= columnCount; i++) {
                        String columnName = resultSetMetaData.getColumnName(i);
                        String value = resultSet.getString(i);
                        map.put(columnName, value);
                    }
                    mapList.add(map);
                }
                resultSet.close();
                connection.close();
            }
            log.info("最后查询结果-----mapList:{}", mapList);
            return mapList;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return mapList;
    }


    public static int executeUpdate(String driver, String url, String user, String password, String sql) {
        //初始化连接
        Connection connection;
        List<Map<String, String>> mapList = new ArrayList<>();
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, user, password);
            //判断连接是否成功
            if (!connection.isClosed()) {
                Statement statement = connection.createStatement();
                int updateRows = statement.executeUpdate(sql);
                log.info("更新成功，影响条数：{}",updateRows);
                return updateRows;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return 0;
    }
}
